import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Dimensions,
    Modal,
    Platform,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../res/styles/StyleUtils";
import ViewUtils from "./ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE} from "../httpUtils/IparNetwork";
import I18n from '../res/language/i18n';

let height = Dimensions.get('window').height;
export default class VerificationCodeInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            isFocused: true,
            isFocusedIndex: 0,
            verificationTimer: I18n.t('default.sendVerCode'),
            timerEnd: true,
            textString: '',
            bottomHeight: 0,
        };

    }


    /**
     * 默认value
     */

    defaultProps: {
        inputSize: 6,
    };


    propTypes: {
        inputSize: PropTypes.number,
    };


    /**
     * SendVerificationCode
     */
    onLoadData() {

        if (!this.state.timerEnd) {
            return
        }


        if (!this.props.userInfo) {
            DeviceEventEmitter.emit(I18n.t('default.fail'));
            return
        }
        // 正在发送验证码 效果
        this.setState({
            timerEnd: false,
            verificationTimer: I18n.t('default.loading')
        });

        let data = {
            Auth: getSynPaysSellerAuth(this.props.country, 1),
            UserID: this.props.userInfo.main_user_id,
            VerifyMethod: this.props.VerifyMethod,
        };
        new IparNetwork().getPostJson(SERVER_TYPE.synPays + 'SendVerificationCode', data)
            .then((result) => {

                if (result.ApiResponseCode === 200) {
                    DeviceEventEmitter.emit(I18n.t('default.success'));

                    this.countTime();
                } else {
                    DeviceEventEmitter.emit(I18n.t('default.fail'));
                    this.setState({
                        verificationTimer: I18n.t('toast.againGetCode'),
                        timerEnd: true,
                    });

                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit(I18n.t('default.fail'));
                this.setState({
                    verificationTimer: I18n.t('toast.againGetCode'),
                    timerEnd: true,
                });
                console.log('VerificationCodeInput----error: ', error)
            })
    }

    /**
     * 发送验证码的效果（btn 的 文字（59...））
     */
    countTime() {
        this._index = 60;
        this._timer = setInterval(() => {
            this.setState({
                verificationTimer: this._index-- + ' s',
                timerEnd: false
            });
            if (this.state.verificationTimer <= 0 + ' s') {
                this._timer && clearInterval(this._timer);
                this.setState({
                    verificationTimer: I18n.t('toast.againGetCode'),
                    timerEnd: true,
                });
            }
        }, 1000);
    }

    /**
     * stopTime
     */
    stopTime() {
        this._timer && clearInterval(this._timer);
        this.setState({
            verificationTimer: I18n.t('toast.againGetCode'),
        });
    }

    /**
     * finish page的时候
     */
    componentWillUnmount() {
        this._timer && clearInterval(this._timer);
    }


    /**
     * 刷新props
     * @param nexProps
     */
    componentWillReceiveProps(nexProps) {
        if (this.state.visible !== nexProps.visible) {
            if (nexProps.visible && nexProps.inputSize === 6) {
                this.onLoadData();
            }

            this.setState({
                visible: nexProps.visible,
            });
        }
    }


    /**
     *   初始化 text
     * @param callback
     * @returns {Array}
     */
    renderText(callback) {
        let inputs = [];
        for (let i = 0; i < this.props.inputSize; i++) {

            let _style = null;
            if (this.state.textString.length === i) {
                _style = styles.focusText
            } else {

                if (this.state.textString.length > 0) {
                    _style = {borderColor: '#a6a6a6'}
                } else if (this.props.message) {
                    _style = {borderColor: '#ff574b'}
                }

            }

            inputs.push(
                <Text
                    key={i}
                    style={[styles.text, _style]}>
                    {this.state.textString[i]}
                </Text>
            )
        }

        return inputs
    }

    onLayout(event) {
        this.setState({
            bottomHeight: height - event.nativeEvent.layout.height
        })
    }


    /**
     * close modal 方法
     * */
    onRequestClose() {
        // this.stopTime();
        this.props.close(null)
    }


    /**
     *
     * 获取加密的account
     * 13079948999 => 13***8999
     * nur01@qq.com => nu***01@qq.com
     * */
    getUserAccount() {

        let userAccount = '';
        let userInfo = this.props.userInfo;
        if (userInfo) {

            if (this.props.VerifyMethod === 1) {//email
                if (userInfo.email) {
                    let email = userInfo.email;
                    let index = email.indexOf('@');
                    if (index > 3) {
                        let leftStr = email.substring(0, 2);
                        let ringhtSrt = email.substring(index - 2, email.length);
                        userAccount = leftStr + '***' + ringhtSrt
                    } else {
                        let ringhtSrt = email.substring(index - (index - 2), email.length);
                        userAccount = '***' + ringhtSrt
                    }
                } else {
                    userAccount = I18n.t('default.no')//'没有email';
                }
            } else {//mobile
                if (userInfo.mobile) {
                    if (userInfo.mobile > 6) {
                        let length = userInfo.mobile.length;
                        let leftStr = userInfo.mobile.substring(0, 2);
                        let ringhtStr = userInfo.mobile.substring(length - 4, length);
                        userAccount = leftStr + '******' + ringhtStr
                    } else {
                        let ringhtStr = userInfo.mobile.substring(length - (length - 2), length);
                        userAccount = '***' + ringhtStr
                    }
                } else {
                    userAccount = I18n.t('default.no')//'没有mobile';
                }
            }
        }

        return userAccount;
    }


    componentDidUpdate() {
        //输入完毕
        if (this.state.textString.length === this.props.inputSize) {
            this.props.onChangeText(this.state.textString);

            this.setState({
                textString: '',
            })
        }
    }

    render() {

        let typeIsVerification = this.props.inputSize === 6;

        return (
            <Modal
                style={[StyleUtils.flex, StyleUtils.center]}
                onRequestClose={() => this.onRequestClose()}
                animationType={'slide'}
                transparent={true}
                visible={this.state.visible}
            >


                <View
                    style={[StyleUtils.flex, styles.boxStyle]}
                >
                    <KeyboardAwareScrollView
                        style={[StyleUtils.flex, styles.boxStyle]}
                    >

                        <View
                            onLayout={(event) => this.onLayout(event)}
                            style={[styles.listBoxStyle, {marginTop: this.state.bottomHeight}]}>

                            <View style={[StyleUtils.justifySpace,]}>

                                <Text
                                    style={[styles.title, StyleUtils.smallFont]}>
                                    {this.props.inputSize === 6 ? I18n.t('default.sendVerCode') : I18n.t('toast.enterCvv')}
                                </Text>

                                {/**close btn*/}
                                {ViewUtils.getImageBtnView({
                                        padding: 8,
                                        margin: 8
                                    }, require('../res/images/ic_close.png'),
                                    [StyleUtils.tabIconSize, {tintColor: '#333333'}],
                                    () => {
                                        this.onRequestClose()
                                    },
                                    '#ebebeb')}
                            </View>


                            <Text
                                style={[styles.accountName, StyleUtils.smallFont]}>{
                                typeIsVerification ? this.getUserAccount() : ''
                            }</Text>
                            <Text
                                style={styles.accountName}>{this.props.message ? this.props.message : this.props.centerValue}</Text>

                            <View style={typeIsVerification ? null : {marginBottom: 80}}>
                                {/**text*/}
                                <View style={[styles.textBox, StyleUtils.rowDirection, StyleUtils.center]}>
                                    {this.renderText()}
                                </View>


                                {/**input*/}
                                <TextInput
                                    style={[styles.intextInputStyle, StyleUtils.smallFont]}
                                    onChangeText={(text) => {
                                        this.setState({
                                            textString: text,
                                        });
                                    }}
                                    value={this.state.textString}
                                    underlineColorAndroid="transparent"
                                    maxLength={this.props.inputSize}
                                    autoFocus={true}
                                    keyboardType="numeric"
                                    selectionColor="transparent"
                                />
                            </View>

                            {typeIsVerification ?
                                <TouchableOpacity
                                    onPress={() => this.onLoadData()}
                                >
                                    <Text style={[styles.verification_Code, StyleUtils.smallFont]}>
                                        {this.state.verificationTimer}
                                    </Text>
                                </TouchableOpacity>
                                : null
                            }

                        </View>
                    </KeyboardAwareScrollView>
                </View>
            </Modal>
        )


    }


}

const
    styles = StyleSheet.create({
        boxStyle: {
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
        },
        textBox: {
            position: 'absolute',
            left: 0,
            right: 16,
        },
        accountName: {
            marginTop: 16,
            height: 40,
            fontSize: 16,
            width: '100%',
            textAlign: 'center',
            color: '#939393'
        },

        title: {
            flex: 1,
            marginLeft: 52,
            textAlign: 'center',
            fontSize: 18,
            color: '#333333'
        },

        listBoxStyle: {
            backgroundColor: 'white',
            width: '100%',
        },

        verification_Code: {
            fontSize: 16,
            width: '100%',
            marginBottom: 80,
            marginTop: 26,
            textAlign: 'center',
            color: '#939393'
        },
        text: {
            height: 40,
            width: 40,
            lineHeight: Platform.OS === 'ios' ? 40 : 35,
            borderWidth: 1,
            borderColor: '#cdcdcd',
            color: 'black',
            fontSize: 25,
            marginLeft: 16,
            textAlign: 'center'
        },
        focusText: {
            borderColor: 'black',
        },
        inputItem: {
            lineHeight: 20,
            width: 80,
            textAlign: 'center',
            height: 40,
        },
        intextInputStyle: {
            width: '100%',
            height: 40,
            fontSize: 25,
            color: 'transparent',
        },
    });
